﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Interface;
using Lamex.Library.CommonClass;
using System.IO;
using Lamex.Base;
using Lamex.mTools.UI;

namespace Lamex.mPE.UI
{
    public partial class frmPE_Main : frmModuleBase
    {
        DataTable dtPartList = null;
        string strCurPath, strTmpPath, strCurModule, strResult, strNewFile;

        public frmPE_Main()
        {
            InitializeComponent();
            menuStrip1.Text = ModuleNames.mPE; //与AssemblyModuleEntry.ModuleName定义相同
        }
        public override MenuStrip GetModuleMenu()
        {
            return this.menuStrip1;
        }

        private void menuPE_PN_AL_PartList_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("NC_PN_AL_Detail_Drawing", 0, true, false), sender as ToolStripMenuItem);
        }

        private void menuPE_PN_AL_PartPara_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("NC_PN_AL_Detail_Part", 0, true, false), sender as ToolStripMenuItem);
        }

        private void menuPE_PN_AL_BasicModule_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("NC_PN_AL_Section_Info", 0, true, true), sender as ToolStripMenuItem);
        }

        private void menuPE_PN_AL_BatchModeling_Click(object sender, EventArgs e)
        {
            #region //选择模型文件路径
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = false;
            dialog.Description = "请选择模型文件路径，拆分实例保存在同级路径：" + "\r\n" + "再次实例化前请先删除旧文件！";
            dialog.SelectedPath = @"L:\Parametric\Sample";
            //dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                strCurPath = dialog.SelectedPath;
                strCurModule = strCurPath.Substring(strCurPath.LastIndexOf("\\") + 1, strCurPath.Length - strCurPath.LastIndexOf("\\") - 1);
                strTmpPath = strCurPath.Substring(0, strCurPath.Length - strCurModule.Length - 1) + "\\Temp";
                if (Directory.Exists(strTmpPath))//文件夹存在
                {
                    DirectoryInfo di = new DirectoryInfo(strTmpPath);
                    di.Delete(true);//删除里面所有的文件，包括文件夹和子文件夹
                }
                Directory.CreateDirectory(strTmpPath);//创建文件夹
            }
            else
            {
                return;
            }
            #endregion

            #region //获取处理清单

            //            string sql = @"SELECT * FROM [LamexMESManager].[dbo].[NC_PN_AL_Detail_Part]
            //                            WHERE DRAWING_NO = '" + strCurModule + "'" +
            //                            "ORDER BY PART_NO";

            //string sql = @"select a.*,b.CREO_VALUE_TYPE from 
            //            (select p.DRAWING_NO + '_' + p.PARAMETER_NAME as DWG_PAR,p.* from NC_PN_AL_Detail_Part p) a 
            //            left join 
            //            (select d.DRAWING_NO + '_' + d.PARAMETER_NAME as DWG_PAR,d.CREO_VALUE_TYPE from NC_PN_AL_Detail_Drawing d) b 
            //            on b.DWG_PAR=a.DWG_PAR
            //            where a.DRAWING_NO='" + strCurModule + "'";

            //增加按PART_NO排序，避免因多参数图纸（A6FA248A）创建文件夹时报错中断，2020/6/18 Rocky
            string sql = @"select a.*,b.CREO_VALUE_TYPE from 
                        (select p.DRAWING_NO + '_' + p.PARAMETER_NAME as DWG_PAR,p.* from NC_PN_AL_Detail_Part p) a 
                        left join 
                        (select d.DRAWING_NO + '_' + d.PARAMETER_NAME as DWG_PAR,d.CREO_VALUE_TYPE from NC_PN_AL_Detail_Drawing d) b 
                        on b.DWG_PAR=a.DWG_PAR
                        where a.DRAWING_NO='" + strCurModule + @"'
                        order by PART_NO";

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);

            #endregion

            if (dt.Rows.Count != 0)
            {
                #region //拆分实例模型
                string prePART_NO = "", curPART_NO = "", curMODEL_NO = "", strParFile = "";
                string strParList = "", strCfgList = "";
                string parName = "", parValue = "";

                strCfgList = @"mapkey pmd ~ Command `ProCmdModelEraseNotDisp` ;\" + "\r\n";

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    curPART_NO = dt.Rows[i]["PART_NO"].ToString();

                    if (curPART_NO != prePART_NO)//不同部件才进行拆分                
                    {
                        if (strParList != "")
                        {
                            File.WriteAllText(strParFile, strParList, Encoding.UTF8);
                            strParList = "";
                        }
                     
                        prePART_NO = curPART_NO;
                        curMODEL_NO = strCurModule + "_" + curPART_NO;
                        var newPath = strTmpPath + "\\" + curMODEL_NO;
                        strParFile = newPath + "\\" + curMODEL_NO + ".txt";

                        strParList = strParList + "PART_NO = " + "\"" + curPART_NO + "\"" + "\r\n";

                        parName = dt.Rows[i]["PARAMETER_NAME"].ToString();
                        parValue = dt.Rows[i]["PARAMETER_VALUE"].ToString();

                        if (dt.Rows[i]["CREO_VALUE_TYPE"].ToString() == "String")
                        {
                            strParList = strParList + parName + " = " + "\"" + parValue + "\"" + "\r\n";
                        }
                        else
                        {
                            strParList = strParList + parName + " = " + parValue + "\r\n";
                        }

                        //复制所有文件
                        Directory.CreateDirectory(newPath);
                        string[] filenames = Directory.GetFileSystemEntries(strCurPath);
                        foreach (string file in filenames)
                        {
                            strNewFile = file.Substring(file.LastIndexOf("\\") + 1, file.Length - file.LastIndexOf("\\") - 1);
                            File.Copy(file, newPath + "\\" + strNewFile);
                        }
                       
                        strCfgList = strCfgList
                        + @"mapkey(continued) ~ Activate `file_erase_nd` `ok_pb`;~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `file_open` `Inputname` \" + "\r\n"
                        + @"mapkey(continued) `" + @newPath.Replace(@"\",@"\\") + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProCmdModelOpen` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `file_open` `Inputname` `" + strCurModule + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdModelRename` ;\" + "\r\n"
                        + @"mapkey(continued) ~ Update `rename` `InputPanel2` `" + curMODEL_NO + @"`;\" + "\r\n"
                        + @"mapkey(continued) ~ Activate `rename` `OK`;~ Command `ProCmdRegenPart` ;#READ FILE;\" + "\r\n"
                        + @"mapkey(continued) " + strParFile + @";\" + "\r\n";

                        //因增加自动切换当前工作目录快捷指令，所以代码注释掉，2019-12-24
                        //if (i != dt.Rows.Count - 1)
                        //{
                        strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;\" + "\r\n";
                        //}
                        //else
                        //{
                            //strCfgList = strCfgList + @"mapkey(continued) ~ Command `ProCmdModelSave` ;~ Command `ProCmdWinCloseGroup`;" + "\r\n";
                        //}
                    }
                    else
                    {
                        strParList = strParList + dt.Rows[i]["PARAMETER_NAME"].ToString() + " = " + dt.Rows[i]["PARAMETER_VALUE"].ToString() + "\r\n";
                    }         
                }

                //增加自动切换当前工作目录到D:\快捷指令，2019-12-24
                strCfgList = strCfgList
                + @"mapkey(continued) ~ Command `ProCmdSessionChangeDir` ;\" + "\r\n"
                + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `file_open` `computer_pb`;\" + "\r\n"
                + @"mapkey(continued) ~ Select `file_open` `Ph_list.Filelist` 1 `d:`;\" + "\r\n"
                + @"mapkey(continued) ~ Command `ProFileSelPushOpen@context_dlg_open_cmd`;" + "\r\n"
                + @"" + "\r\n"
                + @"" + "\r\n";

                //最后一个部件参数文件输出
                File.WriteAllText(strParFile, strParList, Encoding.UTF8);

                #endregion

                #region //生成批处理命令配置文件

                //切换标准配置文件命令输出
                strCfgList = strCfgList + "\r\n"
                + @"mapkey cf ~ Select `main_dlg_cur` `appl_casc`;\" + "\r\n"
                + @"mapkey(continued) ~ Close `main_dlg_cur` `appl_casc`;~ Command `ProCmdRibbonOptionsDlg` ;\" + "\r\n"
                + @"mapkey(continued) ~ Select `ribbon_options_dialog` `PageSwitcherPageList` 1 `ConfigLayout`;\" + "\r\n"
                + @"mapkey(continued) ~ Select `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ Close `ribbon_options_dialog` `ConfigLayout.ImportExportBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `ConfigLayout.Open`;\" + "\r\n"
                + @"mapkey(continued) ~ Trail `UI Desktop` `UI Desktop` `DLG_PREVIEW_POST` `file_open`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `main_dlg_cur` `main_dlg_cur`;\" + "\r\n"
                + @"mapkey(continued) ~ Update `file_open` `Inputname` `Z:\\Sta\\Rocky he\\Config.pro`;\" + "\r\n"
                + @"mapkey(continued) ~ Command `ProFileSelPushOpen_Standard@context_dlg_open_cmd` ;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `ribbon_options_dialog` `OkPshBtn`;\" + "\r\n"
                + @"mapkey(continued) ~ FocusIn `UITools Msg Dialog Future` `no`;\" + "\r\n"
                + @"mapkey(continued) ~ Activate `UITools Msg Dialog Future` `no`;" + "\r\n";

                //批量抽取特征数据时不能识别数字版本，所以设置直接保存
                strCfgList = strCfgList + "\r\n"
                + @"save_file_iterations no" + "\r\n";

                File.WriteAllText(@"D:\Config_Temp.pro", strCfgList, Encoding.UTF8);
                #endregion

                MessageBox.Show("在Creo环境下，输入ct导入临时配置文件，用pmd命令完成实例模型刷新！");
            }
            else
            {
                MessageBox.Show("未找到【" + strCurModule + "】部件参数清单，请先维护！");
            }
        }

        private void menuPE_PN_AL_ModelRelease_Click(object sender, EventArgs e)
        {
            String srcPath;//源路径
            string desPath = @"\\Tx-fs10\tx-fs1\LAMEX\Parametric\Module\For_NC";//目标路径

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = false;
            dialog.Description = "请选择文件路径";
            dialog.SelectedPath = @"L:\Parametric\Sample";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                srcPath = dialog.SelectedPath;

                //1、判断是否只包含一级子目录，且只包含一个图号（一次只能发布一张图纸），否则提示并退出
                //TO DO
                //2、判断一级目录（图号_部件号）是否已发布，即检查图号是否出现在[NC_PN_AL_Detail_Part]表中,
                //   如果出现，则再检查发布时间是否为空；满足此两个条件，则提示用户是选择重新发布，还是直接退出
                //TO DO
                //3、重新发布前，删除当前图号相关信息，逻辑待定
                //TO DO

                //4、图纸发布（复制）子程序
                if (CopyFoldersWithSubDir(srcPath, desPath))
                {
                    MessageBox.Show("模型发布成功！");
                }
                else
                {
                    MessageBox.Show("模型发布失败！");
                }
            }
        }

        /// <summary>
        /// 拷贝srcPath的文件到desPath下面
        /// </summary>
        /// <param name="srcPath">源路径(@"用户指定")</param>
        /// <param name="desPath">目标路径(@"\\Tx-fs10\tx-fs1\LAMEX\Parametric\Part")</param>
        /// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
        public bool CopyFoldersWithSubDir(string srcPath, string desPath)
        {
            if (!Directory.Exists(desPath))
            {
                Directory.CreateDirectory(desPath);
            }
            #region //拷贝文件夹到desPath下
            try
            {
                string[] partDirs = Directory.GetDirectories(srcPath);//目录
                string[] partFiles = Directory.GetFiles(srcPath);//文件
                if (partFiles.Length > 0)
                {
                    for (int i = 0; i < partFiles.Length; i++)
                    {
                        if (Path.GetExtension(partFiles[i]) != ".xlsx")//排除.xlsx文件
                        {
                            File.Copy(srcPath + "\\" + Path.GetFileName(partFiles[i]), desPath + "\\" + Path.GetFileName(partFiles[i]), true);
                        }
                    }
                }
                if (partDirs.Length > 0)
                {
                    for (int j = 0; j < partDirs.Length; j++)
                    {
                        Directory.GetDirectories(srcPath + "\\" + Path.GetFileName(partDirs[j]));
                        //递归调用
                        CopyFoldersWithSubDir(srcPath + "\\" + Path.GetFileName(partDirs[j]), desPath + "\\" + Path.GetFileName(partDirs[j]));
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
            #endregion
            return true;
        }

        /// <summary>
        /// 根据路径删除文件或文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFile(string path)
        {
            FileAttributes attr = File.GetAttributes(path);
            if (attr == FileAttributes.Directory)
            {
                Directory.Delete(path, true);
            }
            else
            {
                File.Delete(path);
            }
        }
  
        /// <summary>
        /// Recursively delete all the files and folders under the specific path.
        /// 递归删除某一路径下的所有文件和文件夹
        /// </summary>
        /// <param name="path">The specific path.</param>
        private static void DeleteFilesAndFolders(string path)
        {
            // Delete files.
            string[] files = Directory.GetFiles(path);
            foreach (var file in files)
            {
                File.Delete(file);
            }
 
            // Delete folders.
            string[] folders = Directory.GetDirectories(path);
            foreach (var folder in folders)
            {
                DeleteFilesAndFolders(folder);
                Directory.Delete(folder);
            }
        }

        private void menuPE_Image_Brower_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildForm(this.MdiParent as IMdiForm, typeof(frmTL_Image_Brower), sender as ToolStripMenuItem);
        }

        private void menuPE_Search_Part_Image_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildForm(this.MdiParent as IMdiForm, typeof(frmTL_Image_Brower), sender as ToolStripMenuItem);
        }

        private void menuPE_Search_Accessory_Image_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildForm(this.MdiParent as IMdiForm, typeof(frmTL_Image_Accessories), sender as ToolStripMenuItem);
        }

        private void menuPE_Search_Product_Image_Click(object sender, EventArgs e)
        {
            MdiTools.OpenChildForm(this.MdiParent as IMdiForm, typeof(frmTL_Image_Accessories), sender as ToolStripMenuItem);
        }
    }
}